//
//  YYRouter.swift
//  YYProject
//
//  Created by 陆文宇 on 2017/8/11.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import Foundation

enum YYRouteType {
    case push
    case present
}

struct YYRoute {
    
    typealias Key = String
    
    var key: String?
    var controller: YYController.Type
    var openType: YYRouteType
    var needValidateLogin: Bool
}

final class YYRouter {
    
    static var currentVC: YYController!
    
    private static var routes = initRoutes()
    
    static func getRoute(of routeKey: String) -> YYRoute? {
        return routes[routeKey]
    }
    
    static func getWebUrl(routeKey: String, params: [String: Any]) -> String? {
        if let route = getRoute(of: routeKey) {
            if let routeUrl = route.key {
                return getUrlString(routeUrl: routeUrl, params: params)
            } else {
                return nil
            }
        } else {
            return getUrlString(routeUrl: routeKey, params: params)
        }
    }
    
    static func pushToVC(of routeKey: String, params: [String: Any]) {
        if let route = getRoute(of: routeKey) {
            var params = params
            if route.needValidateLogin && !validateLogin() {
                gotoLogin()
            } else {
                let vc = route.controller.init()
                vc.routeKey = routeKey
                if let routeUrl = route.key {
                    if route.needValidateLogin {
                        params["token"] = YYAppConfig.getOne(key: appConfig_user_token)
                    }
                    (vc as! YYWebController).yy_webUrl = getUrlString(routeUrl: routeUrl, params: params)
                } else {
                    params["routeKey"] = routeKey
                    vc.setValuesForKeys(params)
                }
                
                switch route.openType {
                case .push:
                    vc.hidesBottomBarWhenPushed = true
                    currentVC.navigationController?.pushViewController(vc, animated: true)
                case .present:
                    let nc = UINavigationController(rootViewController: vc)
                    currentVC.present(nc, animated: true, completion: nil)
                }
            }
        } else {
            let urlString = getUrlString(routeUrl: routeKey, params: params)
            pushToWebVC(url: urlString)
        }
    }
    
    static func pushToWebVC(url: String) {
        let webVC = YYWebController(nibName: nil, bundle: nil)
        webVC.yy_webUrl = url
        webVC.hidesBottomBarWhenPushed = true
        currentVC.navigationController?.pushViewController(webVC, animated: true)
    }

}

